/**
 * AI客户端JavaScript模块
 * 为前端提供统一的AI服务调用接口
 */

class AIClient {
    constructor(baseUrl = 'http://localhost:8001') {
        this.baseUrl = baseUrl;
        this.activeProvider = null;
        this.cache = new Map();
        this.cacheTimeout = 30 * 60 * 1000; // 30分钟
    }

    /**
     * 获取可用AI提供商
     */
    async getProviders() {
        try {
            const response = await fetch(`${this.baseUrl}/providers`);
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('获取AI提供商失败:', error);
            throw error;
        }
    }

    /**
     * 切换AI提供商
     */
    async switchProvider(provider) {
        try {
            const response = await fetch(`${this.baseUrl}/switch-provider`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ provider })
            });
            
            const data = await response.json();
            if (data.success) {
                this.activeProvider = provider;
                console.log(`已切换到 ${provider} 提供商`);
            }
            return data;
        } catch (error) {
            console.error('切换AI提供商失败:', error);
            throw error;
        }
    }

    /**
     * 通用AI聊天
     * @param {string} message - 用户消息
     * @param {string} context - 上下文信息
     * @returns {Promise<Object>} AI响应
     */
    async chat(message, context = '') {
        try {
            const response = await fetch(`${this.baseUrl}/api/ai/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    context: context
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('AI聊天请求失败:', error);
            throw error;
        }
    }

    /**
     * 流式AI聊天（支持GLM流式输出）
     * @param {string} message - 用户消息
     * @param {string} context - 上下文信息
     * @param {Function} onChunk - 接收每个数据块的回调函数
     * @returns {Promise<void>}
     */
    async chatStream(message, context = '', onChunk = null) {
        try {
            const response = await fetch(`${this.baseUrl}/api/ai/chat/stream`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    context: context
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = line.slice(6);
                        if (data === '[DONE]') return;
                        
                        try {
                            const parsed = JSON.parse(data);
                            if (onChunk && parsed.content) {
                                onChunk(parsed.content);
                            }
                        } catch (e) {
                            console.error('解析流式数据失败:', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('流式AI聊天请求失败:', error);
            throw error;
        }
    }

    /**
     * 需求预测
     */
    async demandForecast(productId, options = {}) {
        try {
            const response = await fetch(`${this.baseUrl}/demand-forecast`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    product_id: productId,
                    forecast_periods: options.periods || 12,
                    historical_data_months: options.historicalMonths || 24,
                    include_seasonality: options.seasonality !== false
                })
            });

            return await response.json();
        } catch (error) {
            console.error('需求预测失败:', error);
            throw error;
        }
    }

    /**
     * 异常检测
     */
    async anomalyDetection(data, options = {}) {
        try {
            const response = await fetch(`${this.baseUrl}/anomaly-detection`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    data: data,
                    threshold: options.threshold || 2.0,
                    method: options.method || 'isolation_forest'
                })
            });

            return await response.json();
        } catch (error) {
            console.error('异常检测失败:', error);
            throw error;
        }
    }

    /**
     * 供应商分析
     */
    async supplierAnalysis(supplierId, options = {}) {
        try {
            const response = await fetch(`${this.baseUrl}/supplier-analysis`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    supplier_id: supplierId,
                    analysis_type: options.type || 'performance',
                    time_range: options.timeRange || '12m'
                })
            });

            return await response.json();
        } catch (error) {
            console.error('供应商分析失败:', error);
            throw error;
        }
    }

    /**
     * 库存优化
     */
    async inventoryOptimization(productId, currentStock, options = {}) {
        try {
            const response = await fetch(`${this.baseUrl}/inventory-optimization`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    product_id: productId,
                    current_stock: currentStock,
                    lead_time: options.leadTime || 7,
                    service_level: options.serviceLevel || 0.95
                })
            });

            return await response.json();
        } catch (error) {
            console.error('库存优化失败:', error);
            throw error;
        }
    }

    /**
     * 健康检查
     */
    async healthCheck() {
        try {
            const response = await fetch(`${this.baseUrl}/health`);
            return await response.json();
        } catch (error) {
            console.error('健康检查失败:', error);
            throw error;
        }
    }

    /**
     * 生成缓存键
     */
    generateCacheKey(type, params) {
        const str = JSON.stringify({ type, params });
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return hash.toString();
    }

    /**
     * 清除缓存
     */
    clearCache() {
        this.cache.clear();
        console.log('AI客户端缓存已清除');
    }

    /**
     * 获取缓存统计
     */
    getCacheStats() {
        return {
            size: this.cache.size,
            timeout: this.cacheTimeout
        };
    }
}

// 便捷函数
class AIUtils {
    /**
     * 格式化AI响应为HTML
     */
    static formatResponse(content) {
        // 将JSON响应格式化为HTML
        try {
            const jsonMatch = content.match(/\{[\s\S]*\}/);
            if (jsonMatch) {
                const jsonData = JSON.parse(jsonMatch[0]);
                return this.jsonToHtml(jsonData);
            }
        } catch (e) {
            // 如果不是JSON，按普通文本处理
        }
        
        return content.replace(/\n/g, '<br>');
    }

    /**
     * JSON转HTML
     */
    static jsonToHtml(obj, indent = 0) {
        const spaces = '  '.repeat(indent);
        if (Array.isArray(obj)) {
            return obj.map(item => 
                `${spaces}<li>${this.jsonToHtml(item, indent + 1)}</li>`
            ).join('');
        } else if (typeof obj === 'object' && obj !== null) {
            return Object.entries(obj).map(([key, value]) => 
                `${spaces}<div><strong>${key}:</strong> ${this.jsonToHtml(value, indent + 1)}</div>`
            ).join('');
        } else {
            return String(obj);
        }
    }

    /**
     * 显示加载状态
     */
    static showLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> AI分析中...</div>';
        }
    }

    /**
     * 隐藏加载状态
     */
    static hideLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            const loading = element.querySelector('.loading');
            if (loading) {
                loading.remove();
            }
        }
    }

    /**
     * 显示错误信息
     */
    static showError(elementId, error) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = `<div class="alert alert-danger">错误: ${error}</div>`;
        }
    }

    /**
     * 显示成功信息
     */
    static showSuccess(elementId, message) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = `<div class="alert alert-success">${message}</div>`;
        }
    }
}

// 全局实例
const aiClient = new AIClient();

// 使用示例
/*
// 初始化
const client = new AIClient();

// 获取提供商
client.getProviders().then(providers => {
    console.log('可用提供商:', providers);
});

// 需求预测
client.demandForecast('PROD001', {
    periods: 6,
    historicalMonths: 12
}).then(result => {
    console.log('预测结果:', result);
});

// 异常检测
client.anomalyDetection([
    { date: '2024-01', value: 100 },
    { date: '2024-02', value: 120 }
]).then(result => {
    console.log('检测结果:', result);
});
*/

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { AIClient, AIUtils };
} else {
    window.AIClient = AIClient;
    window.AIUtils = AIUtils;
    window.aiClient = aiClient;
}